<?php
/**
 * Created by PhpStorm.
 * User: lzh 9157374
 * Date: 2018/7/1
 * Time: 下午5:40
 */
namespace app\controller;
use Core\common\Wechat;
class index extends _base
{
    public function __construct()
    {
        parent::__construct();
    }


    public function index()
    {
        $activity = M('activity')->getData();
        if(!$activity) return $this->create_json_info('error', '未找到该的活动', '', '1002');

        if($activity['status'] == 2) return $this->create_json_info('error', '活动未开始', '', '1002');
        //活动时间判断
        if($activity['start_time'] > time()) return $this->create_json_info('error', '活动未开始', '', '1002');

        if($activity['end_time'] < time()) return $this->create_json_info('error', '活动已结束', '', '1002');

        $activity['background'] = tomedia($activity['background']);

        $activity['chart'] = $this->img($activity['chart'],'chart');

        $activity['banner'] = tomedia($activity['banner']);

        $activity['content'] = htmlspecialchars_decode($activity['content']);
        $activity['service'] = htmlspecialchars_decode($activity['service']);
        $this->create_json_info('success', '成功', compact('activity'));
    }

    /**
     * 随机商品
     */
    public function rand(){
        $aParams['field'] = ['status','start_time','end_time'];
        $activity = M('activity')->getData($aParams);
        if(!$activity) return $this->create_json_info('error', '未找到该的活动', '', '1002');

        if($activity['status'] == 2) return $this->create_json_info('error', '活动未开始', '', '1002');
        //活动时间判断
        if($activity['start_time'] > time()) return $this->create_json_info('error', '活动未开始', '', '1002');

        if($activity['end_time'] < time()) return $this->create_json_info('error', '活动已结束', '', '1002');

        $rand = $this->todo_draw();
        if(!$rand) return $this->create_json_info('error', '商品库存不足', '', '1002');

        $code = M('code')->getData(['field'=> ['code_id','code'],'where'=>['code_id'=>$rand]]);
        $this->create_json_info('success', '成功', compact('code'));
    }

    /**
     * 奖池
     */
    private function todo_draw() {
        // 获取所有奖品
        $prize_list = M('code')->top([
            'field'     => ['code_id','code','rand','stock_num','sale_num'],
        ]);
        if (empty($prize_list) || !is_array($prize_list)) {
            return $this->create_json_info('error', '暂无奖品信息', '', '1002');
        }

        $arr = [];  //根据奖品的中奖率生成一个中奖集合，集合越大，中奖率越准确
        foreach ( $prize_list as $key => $vo ){
            //判断是否有库存 没有库存不参与奖品概率合集
            if( ($vo['stock_num']-$vo['sale_num']) >= 1 ){
                for( $i = 1 ; $i <= $vo['rand'] ; $i++ ){ //循环奖品设置的中奖率 ，
                    array_push( $arr ,$vo['code_id'] ); // 循环将奖品的id添加到中奖的集合中（如果商品A的中奖率为20，那么商品A的id就会咋中奖集合中重复20次）
                }
            }
        }
        if($arr){
            //随机打算数组内中奖id的顺序
            shuffle( $arr );
            $lucky_index = array_rand( $arr , 1 );  //随机从中奖的集合中获取一个中奖的元素（这里返回的是当前元素所在的索引）
            $lucky_id = $arr[$lucky_index];    //这里最终确定了抽中的奖品id

            return $lucky_id;
        }else{
            return false;
        }

    }

    /**
     * 商品下单
     */
    public function OrderPay(){
        if(empty(I('code_id'))){
            $this->create_json_info('error', '缺少参数:code_id','','1001');
        }
        if(empty(I('address'))){
            $this->create_json_info('error', '缺少参数:address','','1001');
        }
        if(empty(I('mobile'))){
            $this->create_json_info('error', '缺少参数:mobile','','1001');
        }
        if(empty(I('realname'))){
            $this->create_json_info('error', '缺少参数:realname','','1001');
        }
        if(empty(I('thumbnail'))){
            $this->create_json_info('error', '缺少参数:thumbnail','','1001');
        }

        //活动
        $activity = M('activity')->getData();
        if(!$activity) return $this->create_json_info('error', '未找到该的活动', '', '1002');

        if($activity['status'] == 2) return $this->create_json_info('error', '活动未开始', '', '1002');
        //活动时间判断
        if($activity['start_time'] > time()) return $this->create_json_info('error', '活动未开始', '', '1002');

        if($activity['end_time'] < time()) return $this->create_json_info('error', '活动已结束', '', '1002');

        //库存判断
        $code = M('code')->getData(['field'=> ['code_id','code','stock_num','sale_num'],'where'=>['code_id'=>I('code_id')]]);
        if(($code['stock_num']-$code['sale_num']) < 1) return $this->create_json_info('error', '库存不足', '', '1002');

        //生成订单
        $user_id = $this->getUserId(I('token'));
        pdo_begin();
        //生成订单
        $OrderInfo = [
            'uniacid'=>uniacid(),
            'user_id'=>$user_id,
            'order_no'=>$this->getOrderNo(),
            'code_id'=>$code['code_id'],
            'shop_price'=>$activity['price'],
            'postage_price'=>$activity['postage'],
            'pay_price'=>$activity['price']+$activity['postage'],
            'wechat_trade_no'=>$this->getWechatTradeNo(),
            'address'=>I('address'),
            'mobile'=>I('mobile'),
            'realname'=>I('realname'),
            'thumbnail'=>I('thumbnail'),
            'creation_date' => time(),
        ];
        //主订单
        if(!$order_id = M('order')->add($OrderInfo)){
            pdo_rollback();
            $this->create_json_info('error', '数据错误','','1001');
        }
        //吊起支付
        $pay = [
            'openid' => $this->getUserOpenid($user_id),
            'money'  => $OrderInfo['pay_price'],
            'order_no' => $OrderInfo['wechat_trade_no'],
        ];
        if(!$jsdk = (new Wechat)->WxPay($pay,'notify_1.php')){
            pdo_rollback();
            $this->create_json_info('error', '数据错误','','1001');
        }
        pdo_commit();
        $this->create_json_info('success', '支付成功', compact('jsdk'));


    }

    /**
     * 订单列表
     */
    public function OrderLists()
    {
        if(empty(I('status'))){
            $this->create_json_info('error', '缺少参数:status','','1001');
        }
        $aParams1['field'] = ['title'];
        $activity = M('activity')->getData($aParams1);

        $user_id = $this->getUserId(I('token'));
        $page = I('page')?I('page'):1;
        $aParams['limit'] = [($page-1)*10,10];
        $aParams['field'] = ['order_id','order_no','thumbnail','shop_price','postage_price','pay_price','status','creation_date'];
        $aParams['where']['user_id'] = $user_id;
        $aParams['where']['status'] = I('status');
        $list = M('order')->lists($aParams);
        foreach ($list as $k=>$v){
            $list[$k]['creation_date'] = date('Y-m-d H:i',$v['creation_date']);
            $list[$k]['thumbnail'] = tomedia($v['thumbnail']);
            $list[$k]['title'] = $activity['title'];
        }
        $this->create_json_info('success', '成功', compact('list'));
    }

    /**
     * 订单详情
     */
    public function OrderInfo(){
        if(empty(I('order_id'))){
            $this->create_json_info('error', '缺少参数:order_id','','1001');
        }
        $aParams['field'] = [
            'a.order_id','a.order_no','b.code','a.shop_price','a.postage_price',
            'a.pay_price','a.status','a.courier_company','a.courier_no','a.creation_date',
            'a.pay_date','a.delivery_date','a.confirm_date','a.address','a.realname','a.thumbnail'];
        $aParams['where'] = ['order_id'=>I('order_id')];
        $aParams['join'] = ['leftJoin'=>[
            ['yyt_manghe_code','b','a.code_id','b.code_id']
        ]];
        $order = M('order')->getData($aParams);

        $aParams1['field'] = ['title'];
        $activity = M('activity')->getData($aParams1);

        $order['title'] = $activity['title'];
        $order['thumbnail'] = tomedia($order['thumbnail']);
        $order['creation_date'] = date('Y-m-d H:i',$order['creation_date']);
        $order['pay_date'] = date('Y-m-d H:i',$order['pay_date']);
        $order['delivery_date'] = date('Y-m-d H:i',$order['delivery_date']);
        $order['confirm_date'] = date('Y-m-d H:i',$order['confirm_date']);
        $this->create_json_info('success', '成功', compact('order'));
    }

    /**
     * 确认收货
     */
    public function OrderConfirm(){
        if(empty(I('order_id'))){
            $this->create_json_info('error', '缺少参数:order_id','','1001');
        }
        $aParams['field'] = ['status',];
        $aParams['where'] = ['order_id'=>I('order_id')];
        $order = M('order')->getData($aParams);
        if(!$order) return $this->create_json_info('error', '未找到该订单', '', '1002');

        if($order['status'] != 3) return $this->create_json_info('error', '订单状态有误', '', '1002');
        M('order')->edit(['status'=>4,'confirm_date'=>time()],$aParams);
        $this->create_json_info('success', '收货成功', '');
    }

    /**
     * @Notes:物流信息
     * @Interface wuliu
     * @author: LZH
     * @Time: 2020/6/30   13:44
     */
    public function wuliu(){
        if(empty(I('order_id'))){
            $this->create_json_info('error', '缺少参数:order_id','','1001');
        }

        $aParams['field'] = ['order_id','status','courier_company','courier_num','courier_no'];
        $aParams['where'] = ['order_id'=>I('order_id')];
        $order = M('order')->getData($aParams);

        $key = 'nCcydWVr3104';						                    //客户授权key
        $customer = '8A9FEF089EFDAA1115E4F68D189F0DBA';					//查询公司编号
        $param = array (
            'com' => $order['courier_num'],		//快递公司编码
            'num' =>  $order['courier_no'],		//快递单号
        );
        //请求参数
        $post_data = array();
        $post_data["customer"] = $customer;
        $post_data["param"] = json_encode($param);
        $sign = md5($post_data["param"].$key.$post_data["customer"]);
        $post_data["sign"] = strtoupper($sign);
        $url = 'http://poll.kuaidi100.com/poll/query.do';	//实时查询请求地址
        $params = "";
        foreach ($post_data as $k=>$v) {
            $params .= "$k=".urlencode($v)."&";		//默认UTF-8编码格式
        }
        $post_data = substr($params, 0, -1);

        //发送post请求
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $result = curl_exec($ch);
        $data = str_replace("\"", '"', $result );
        $data = json_decode($data,true);

        $this->create_json_info('success', '成功', compact('data'));
    }





}